<?php

namespace App\Repository;

use Dingo\Api\Exception\StoreResourceFailedException;
use Illuminate\Support\Facades\Cache;
use Dingo\Api\Http\Request;
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;


/**
 * 获取token的基类
 * Class TokenRepository
 * @package App\Repository
 */
class TokenRepository
{
    /**
     * 32位随机字符串[用三组字符串，进行MD5加密]
     * @return string
     */
    public static function genarateToken()
    {
        $randChar = getRanChars(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $salt = env('TOKEN_SALT');

        return md5($randChar. $timestamp. $salt);
    }

    /**
     * 根据key获取缓存中的值 uid => 缓存中的uid值
     * @param $key
     * @return mixed
     */
    public static function getCurrentTokenVar($key)
    {
        $token = \Request::header('token');
        $vars = Cache::get($token);
        if (!$vars){
            throw new StoreResourceFailedException('tokenssssss无效或者已过期', null, null, [] , 10001);
        }else{
            if (!is_array($vars)){
                $vars = json_decode($vars, true);
            }
            if (array_key_exists($key, $vars)){
                return $vars[$key];
            }else{
                throw new StoreResourceFailedException('尝试获取token变量不存在', null, null, [], 10001);
            }
        }

    }

    /**
     * 获取缓存中的uid
     * @return mixed
     */
    public static function getCurrentUid()
    {
        return self::getCurrentTokenVar('uid');
    }

    /**
     * 检测用户操作是否合法[被检测的UID是否和缓存中的UID一致]
     * @param $checkedUid 被检测的UID
     * @return bool
     */
    public static function isValidOperate($checkedUid)
    {
        if(!$checkedUid){
            throw new SuspiciousOperationException('检测UID时必须传入一个合法的UID', null, null, [], 999);
        }
        $currentOperateUid = self::getCurrentUid();
        if ($checkedUid == $currentOperateUid){
            return true;
        }
        return false;
    }
}